<?php
/**
 * Created by PhpStorm.
 * User: Lyq
 * Date: 2018/8/17
 * Time: 14:08
 */
namespace app\wechat\controller;

use app\common\model\Settings;
use \think\Controller;
use think\Request;
use think\Db;
use think\Session;

class Common extends Controller
{
    public $bandMobile = false;
    protected function _initialize()
    {
        //注册异常处理
        set_exception_handler("wechat_exception_handler");
        //开启数据库事务
        Db::startTrans();
        //全局配置
        $global = Settings::getSettings(H_SETTINGS_GLOBAL,2);
        $this->assign('global',$global);
        $noLoginList = ['Error','Info','Utils'];
        $controller = request()->controller();
        if(!in_array($controller,$noLoginList)){
            //是否微信打开
            //$this->checkWechat();
            ///检测用户是否登录
            $this->checkUser();
        }

    }

    /**
     * 析构函数
     */
    public function __destruct()
    {
        global $wechat_has_exception;
        //根据是否发生异常，决定事务是提交还是回滚
        $wechat_has_exception ? Db::rollback() : Db::commit();
    }

    /**
     * 模板标题
     * @param string $title
     */
    protected function templateTitle($title = "")
    {
        $this->assign("templateTitle", $title);
    }

    /**
     * ajax成功信息
     *
     * @param string $info 信息内容
     * @param array $extra 额外数据
     */
    protected function ajaxSuccess($info = "", $extra = array())
    {
        $result = array(
            "status"=>0,
            "info" => $info,
            "data" => $extra,
        );
        die(json_encode($result, JSON_UNESCAPED_UNICODE));
    }

    /**
     * ajax失败信息
     *
     * @param string $info 信息内容
     * @param array $extra 额外数据
     */
    protected function ajaxError($info = "", $extra = array())
    {
        $result = array(
            "status"=>1,
            "info" => $info,
            "data" => $extra,
        );
        die(json_encode($result, JSON_UNESCAPED_UNICODE));
    }

    //检测是否登录
    private function checkUser()
    {
        if (!session("?H_LOGIN_USER"))
        {
            //判断是否为ajax操作
            if (request()->isAjax())
            {
                $this->ajaxError('请刷新页面重新登录');
            }
            else
            {
                if(session('WECHAT_USER_INFO')){
                    //有微信登录信息 说明需要绑定手机号
                    $this->bandMobile = true;
                }else{
                    $code = trim(input('code'));
                    if(empty($code)){
                        //获取来源地址
                        $nowurl = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['QUERY_STRING'];
                        //获取code
                        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wechat')['appid'].'&redirect_uri='.urlencode($nowurl).'&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect';
                        header("Location:".$url);
                        exit;
                    }

                    //获取openid和access_token
                    $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.config('wechat')['appid'].'&secret='.config('wechat')['appsecret'].'&code='.$code.'&grant_type=authorization_code';
                    $data = https_request($url);
                    $data = json_decode($data,true);
                    if(@$data['errcode'] != ''){
                        $this->showError('微信授权登录，错误码：'.$data['errcode']);
                    }
                    //获取 用户详细信息 公众号绑到开放平台 使用unionid机制 同一个微信用户（在公众号、小程序、app等） 对于 同一个应用主体 openid 各不相同 但是unionid相同
                    $url2 = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$data['access_token'].'&openid='.$data['openid'].'&lang=zh_CN';
                    $data2 = https_request($url2);
                    $data2 = json_decode($data2,true);

                    if(@$data2['errcode'] != ''){
                        $this->showError('微信获取用户信息，错误码：'.$data2['errcode']);
                    }

                    //验证是否注册-使用unionid机制
                    $unionid = $data2['unionid'];
                    $find = Db::name('user')
                        ->where('unionid',$unionid)
                        ->find();

                    if($find){
                        if($find['in_blacklist'] == 1){
                            //拉黑了
                            $this->showError('您的账号已被加入黑名单');
                        }
                        if(empty($find['openid'])){
                            $band = Db::name('user')
                                ->where('id',$find['id'])
                                ->update(['openid'=>$data2['openid'],'update_time'=>now_datetime()]);
                            if(!$band){
                                $this->showError('服务器繁忙，请稍后再试');
                            }
                            $find['openid'] = $data2['openid'];
                        }
                        //保存登录信息
                        session("H_LOGIN_USER", $find);
                    }else{
                        //未绑定手机账号-记录微信信息用于绑定手机号并注册
                        session("WECHAT_USER_INFO",$data2);
                        $this->bandMobile = true;
                    }
                }

            }
        }
        //映射需要绑定手机号
        $this->assign('bandMobile',$this->bandMobile);
    }

    /**
     * 微信判断
     */
    protected function checkWechat(){
        if(!is_wechat()){
            if(request()->isAjax()){
                $this->ajaxError('请在微信浏览器内操作');
            }else{
                $this->showError('请在微信内打开页面');
            }
        }
    }

    /**
     * 错误信息展示
     * @param string $msg
     */
    protected function showError($msg=''){
        $url = url('Error/index').'?msg='.base64_encode(json_encode($msg));
        header("location:".$url);
        die();
    }
    /**
     * 当前用户的ID
     *
     * @return mixed
     */
    protected function currentUserId()
    {
        //当前用户
        $user = session("H_LOGIN_USER");

        return @$user["id"];
    }
}